import { Component, OnInit } from '@angular/core';
import {Departments} from "../departments";
import {ActivatedRoute, Router} from "@angular/router";
import {ResponseUtil} from "../../../../util/response-util";
import {DepartmentsService} from "../departments.service";
import {MsgResult} from "../../../../models/msg-result";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../../util/page-subject";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {MsgConstants} from "../../../../constants/constants";

declare var $;

@Component({
  selector: 'app-department-update',
  templateUrl: './department-update.component.html'
})
export class DepartmentUpdateComponent implements OnInit {

  department :Departments;
  deptForm: FormGroup;
  //定义变量id
  id:string;
  pId:string;

  siteTypes:string;

  siteTypeStr :string;

  treeObj;

  deptType;

  constructor(
      private router : Router,
      private route : ActivatedRoute,
      private responseUtil : ResponseUtil,
      private fb: FormBuilder,
      private pageSubject : PageSubject,
      private dialogService : OneDialogService,
      private departmentsService :DepartmentsService
    ) {
      this.initObject();
    }

  ngOnInit() {
    this.pushPage();
    this.initUpdateFrom();
    this.getSiteTypeData();
  }

  /**
   * 面包屑导航
   */
  pushPage(){
    let path = new Path("权限系统","");
    this.pageSubject.pushPage("部门管理","修改",path);
  }


  //修改部门信息
  onSubmit(){
    this.department = this.deptForm.value;
    this.department.siteType =this.siteTypes;
    this.departmentsService.updateDepartment(this.department).subscribe(
      result =>this.responseUtil.success(result,this.processUpdateResult),
      message =>this.responseUtil.error(message)
    );
  }

  /**
   * 修改成功后调用
   * @param json
   */
  private processUpdateResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message, () => this.cancelUpdateDepartment());
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  //取消修改按钮
  cancelUpdateDepartment(){
    this.router.navigate(['..'],{relativeTo : this.route});
  }


  /**
   * 实例化对象
   */
  private initObject(){
    this.department =new Departments("","","","","","","","","0");
    this.buildForm();
  }

  /**
   * 构造表单
   */
  buildForm(): void {
    this.deptForm = this.fb.group({
      'id': [this.department.id],
      'name': [this.department.name, [
        Validators.required,
        Validators.maxLength(30)
      ]],
      'belongDept': [this.department.belongDept],
      'pId': [this.department.pId],
      'orgId': [this.department.orgId],
      'orgName': [this.department.orgName],
      'siteType': [this.department.siteType,[
        Validators.required
      ]],
      'remark': [this.department.remark],
      'isValid': [this.department.isValid, [
        Validators.required,
        Validators.maxLength(1)
      ]]
    });
    this.deptForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }


  /**
   * 值变化监听
   * @param data
   */
  onValueChanged(data?: any) {
    if (!this.deptForm) {
      return;
    }
    const form = this.deptForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  /**
   * 校验字段
   * @type {{name: string; code: string}}
   */
  formErrors = {
    'name': '',
    'orgName': '',
    'orgId': '',
    'siteType': '',
    'remark': '',
    'isValid': ''
  };

  /**
   * 校验提示信息
   * @type {{name: {required: string; maxlength: string}; code: {required: string; maxlength: string; pattern: string}}}
   */
  validationMessages = {
    'name': {
      'required': '部门名称不能为空',
      'maxlength': '长度不能超过30',
    },
    'siteType': {
      'required': '站点类型不能为空'
    }
  };

  /**
   * 通过id查询
   */
  initUpdateFrom() {
    //获取路由参数
    this.id = this.route.snapshot.params["deptId"];
    this.departmentsService.getDepartmentById(this.id).subscribe(
      result => this.responseUtil.success(result, this.processGetResult),
      error => this.responseUtil.error(error)
    );
  }
  /**
   * id查询成功后调用
   * @param json
   */
  private processGetResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.department = result.data;
      //用于修改的初始化站点类型
      this.siteTypeStr = result.data.siteType;

      this.deptForm.patchValue(this.department);

      this.pId = this.department.pId;
      this.getDepartmentTree(this.department.orgId)
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 获取站点类型数据
   */
  getSiteTypeData() {
    this.departmentsService.getDeptSiteType().subscribe(
      result => this.responseUtil.success(result, this.processGetSiteType),
      error => this.responseUtil.error(error)
    );
  }

  /**
   * @param result
   */
  private processGetSiteType = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      let selectHtml = "";

      //判断站点类型是否存在，进行过滤为空的站点类型
      if (!!this.siteTypeStr){
        for (let siteType of result.data) {
          if(this.siteTypeStr.indexOf(siteType.siteTypeCode)!= -1){
            selectHtml += "<option id=" + siteType.siteTypeCode + " selected='selected' value=" + siteType.siteTypeCode + ">" + siteType.remark + "</option>";
          }else{
            selectHtml += "<option id=" + siteType.siteTypeCode + " value=" + siteType.siteTypeCode + " >" + siteType.remark + "</option>";
          }
        }
      }else{
        for (let siteType of result.data) {
            selectHtml += "<option id=" + siteType.siteTypeCode + " value=" + siteType.siteTypeCode + " >" + siteType.remark + "</option>";
        }
      }

      $("#section_update_site").html(selectHtml);

      this.initSelect();
    }

    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 初始化下拉框
   */
  initSelect() {
    $("#section_update_site").multiselect({
      buttonWidth: "100%",
      buttonText: (options, select)=> {
        if (options.length == 0) {
          return "-- 请选择一条或多条数据 --";
        }
        else {
          let selected = '';
          let selectedValue = '';
          options.each(function (i,elem) {
            //获取名字
            let label = ($(elem).attr('label') !== undefined) ? $(elem).attr('label') : $(elem).html();
            selected += label + ',';
            //获取siteTypeCode值
            let value = ($(elem).attr('value') !== undefined) ? $(elem).attr('value') : $(elem).html();
            selectedValue += value + ',';
          });

          this.siteTypes= selectedValue.substr(0, selectedValue.length - 1);
          return selected.substr(0, selected.length - 2);
        }

      }
    });
  }

  /**
   * 获取组织机构与部门树
   */
  getDepartmentTree(orgId) {
    this.deptType = this.route.snapshot.params["deptType"];
    this.departmentsService.getDepartmentOrgTree(this.deptType,orgId).subscribe(
      result => this.responseUtil.success(result, this.processRegionsTreeResult),
      message => this.responseUtil.error(message)
    );
  }
  /**
   * 对行政区划树结果处理
   * @param result
   */
  private processRegionsTreeResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      //初始化zTree
      this.regioCodezTree(result.data);
      //  添加所属部门名称
      this.addBelongDept(result.data[0].name);

    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  regioCodezTree(data){
    //    zTreee
    let setting = {
      callback: {
        onClick: this.clickTree
      }
    };

    let zNodes =data;

    this.treeObj = $.fn.zTree.init($("#dept_update_ZTree"), setting, zNodes);
  }
  clickTree = (event, treeId, treeNode) =>{
    let id = this.route.snapshot.params["deptId"];
    if(treeNode.id == id || treeNode.pId == id){
      this.dialogService.info("不能选择要修改的部门及其子部门");
    }else{
      if(treeNode.hasOwnProperty("orgId")){
        this.department.orgId = treeNode.orgId;
        this.department.orgName = treeNode.getPath()[0].name;
        this.department.belongDept = treeNode.name;
        this.department.pId = treeNode.id;
      }else{
        this.department.orgId = treeNode.id;
        this.department.orgName = treeNode.name;
        this.department.belongDept = "";
        this.department.pId = "";
      }
      this.deptForm.patchValue(this.department)
    }
  };

  addBelongDept(orgName){
    this.department = this.deptForm.value;
    this.department.orgName = orgName;
    let parentNode = this.treeObj.getNodesByParam("id",this.pId)[0];
    if(parentNode && parentNode.hasOwnProperty("orgId")){
      this.department.belongDept = parentNode.name;
    }
    this.deptForm.patchValue(this.department);
  }
}
